package top.ochiamalu.aioj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.ochiamalu.aioj.domain.entity.Thumb;
import top.ochiamalu.aioj.enums.ThumbTypeEnum;
import top.ochiamalu.aioj.mapper.ThumbMapper;
import top.ochiamalu.aioj.service.ThumbService;
import top.ochiamalu.aioj.strategy.thumb.ThumbStrategy;

import java.util.Map;

/**
 * 点赞服务impl
 *
 * @author ochiamalu
 * @date 2025/03/07
 */
@Service
public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
        implements ThumbService {

    private final Map<ThumbTypeEnum, ThumbStrategy> strategyMap;

    public ThumbServiceImpl(Map<ThumbTypeEnum, ThumbStrategy> strategyMap) {
        this.strategyMap = strategyMap;
    }

    /**
     * 点赞
     *
     * @param targetId 目标ID
     * @param type     点赞类型
     * @return {@link Boolean }
     */
    @Override
    public Boolean thumb(Long targetId, ThumbTypeEnum type) {
        long userId = StpUtil.getLoginIdAsLong();
        ThumbStrategy strategy = strategyMap.get(type);
        if (strategy == null) {
            throw new RuntimeException("不支持的点赞类型: " + type);
        }
        
        LambdaQueryWrapper<Thumb> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Thumb::getUserId, userId);
        strategy.buildQueryCondition(queryWrapper, targetId);
        
        long count = this.count(queryWrapper);
        
        boolean result;
        if (count > 0) {
            result = this.remove(queryWrapper);
            if (result) {
                strategy.handleAfterThumb(targetId, false);
            }
        } else {
            Thumb thumb = new Thumb();
            thumb.setUserId(userId);
            thumb.setTargetId(targetId);
            thumb.setType(type.getValue());
            result = this.save(thumb);
            if (result) {
                strategy.handleAfterThumb(targetId, true);
            }
        }
        
        return result;
    }
}
